package com.asistencia.dao.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.asistencia.dao.interfaces.SemesterDao;
import com.asistencia.domain.Semester;

@Repository
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SemesterJdbc implements SemesterDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<Semester> listAll() throws DataAccessException {
		String SQL = "SELECT * FROM semester ORDER BY idsemester";
		List matches = jdbcTemplate.query(SQL, new RowMapper() {

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				Semester sem = new Semester();
				sem.setIdSemester(rs.getInt("idsemester"));
				sem.setDescription(rs.getString("description"));
				return sem;

			}
		});

		return (matches.size() > 0 ? (List<Semester>) matches : null);
	}

	@Override
	public Semester getById(Integer idSemester) throws DataAccessException {
		String SQL = "SELECT * FROM semester WHERE idsemester =?";
		List matches = jdbcTemplate.query(SQL, new Object[] { idSemester },
				new RowMapper() {
					@Override
					public Object mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Semester sem = new Semester();
						sem.setIdSemester(rs.getInt("idsemester"));
						sem.setDescription(rs.getString("description"));
						return sem;
					}
				});
		return (matches.size() > 0 ? (Semester) matches.get(0) : null);
	}

}
